#!/usr/bin/env python3
"""
RedFire 配置管理工具
"""

import sys
import argparse
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from shared.core.config.unified_adapter import get_service_registry

def show_services():
    """显示所有服务配置"""
    print("🚀 RedFire 服务配置")
    print("=" * 60)
    
    registry = get_service_registry()
    all_services = registry.get_all_services()
    
    for service_name, service in all_services.items():
        if service:
            status = "✅ 启用" if service.enabled else "⏸️ 禁用"
            print(f"📦 {service.name}")
            print(f"   服务名: {service_name}")
            print(f"   端口: {service.port}")
            print(f"   地址: {service.url}")
            print(f"   API文档: {service.api_url}")
            print(f"   状态: {status}")
            print()

def show_databases():
    """显示数据库配置"""
    print("💾 RedFire 数据库配置")
    print("=" * 60)
    
    from shared.core.config.unified_adapter import get_service_adapter
    adapter = get_service_adapter("user_service")
    
    # 显示主数据库
    try:
        primary_db = adapter.get_database_config("primary")
        print("📊 主数据库 (MySQL)")
        print(f"   类型: {primary_db['type']}")
        print(f"   地址: {primary_db['host']}:{primary_db['port']}")
        print(f"   数据库: {primary_db['database']}")
        print(f"   用户: {primary_db['username']}")
        print(f"   连接池: {primary_db['pool_size']}")
        print()
    except Exception as e:
        print(f"❌ 主数据库配置错误: {e}")
    
    # 显示时序数据库
    try:
        timeseries_db = adapter.get_database_config("timeseries")
        print("⏰ 时序数据库 (InfluxDB)")
        print(f"   类型: {timeseries_db['type']}")
        print(f"   地址: {timeseries_db['host']}:{timeseries_db['port']}")
        print(f"   用户: {timeseries_db['username']}")
        print()
    except Exception as e:
        print(f"❌ 时序数据库配置错误: {e}")

def show_cache():
    """显示缓存配置"""
    print("🗄️  RedFire 缓存配置")
    print("=" * 60)
    
    from shared.core.config.unified_adapter import get_redis_config
    
    try:
        redis_config = get_redis_config()
        print("📮 Redis 配置")
        print(f"   地址: {redis_config['host']}:{redis_config['port']}")
        print(f"   数据库: {redis_config['db']}")
        print(f"   连接URL: {redis_config['url']}")
        print(f"   超时: {redis_config['timeout']}s")
        print(f"   最大连接: {redis_config['max_connections']}")
        print()
    except Exception as e:
        print(f"❌ Redis配置错误: {e}")

def show_security():
    """显示安全配置"""
    print("🔒 RedFire 安全配置")
    print("=" * 60)
    
    from shared.core.config.unified_adapter import get_security_config
    
    try:
        security_config = get_security_config()
        print("🔑 JWT 配置")
        print(f"   算法: {security_config['jwt_algorithm']}")
        print(f"   访问令牌过期: {security_config['jwt_access_token_expire_minutes']} 分钟")
        print(f"   刷新令牌过期: {security_config['jwt_refresh_token_expire_days']} 天")
        print()
        
        print("🌐 CORS 配置")
        origins = security_config['cors_origins']
        if len(origins) <= 5:
            for origin in origins:
                print(f"   - {origin}")
        else:
            for origin in origins[:3]:
                print(f"   - {origin}")
            print(f"   - ... 还有 {len(origins) - 3} 个源")
        print()
    except Exception as e:
        print(f"❌ 安全配置错误: {e}")

def validate_config():
    """验证配置"""
    print("🔍 RedFire 配置验证")
    print("=" * 60)
    
    try:
        # 运行配置验证脚本
        import subprocess
        result = subprocess.run([
            sys.executable, 
            str(project_root / "config" / "validate_config.py")
        ], capture_output=True, text=True, cwd=project_root)
        
        print(result.stdout)
        if result.stderr:
            print("错误输出:")
            print(result.stderr)
        
        return result.returncode == 0
    except Exception as e:
        print(f"❌ 配置验证失败: {e}")
        return False

def show_all():
    """显示所有配置"""
    show_services()
    print()
    show_databases()
    print()
    show_cache()
    print()
    show_security()

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="RedFire 配置管理工具")
    parser.add_argument("command", choices=[
        "services", "databases", "cache", "security", "validate", "all"
    ], help="要执行的命令")
    
    args = parser.parse_args()
    
    commands = {
        "services": show_services,
        "databases": show_databases,
        "cache": show_cache,
        "security": show_security,
        "validate": validate_config,
        "all": show_all
    }
    
    command_func = commands.get(args.command)
    if command_func:
        command_func()
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
